package com.asit.config;

import com.asit.interceptor.SessionAuthHandshakeInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.server.support.DefaultHandshakeHandler;

import java.security.Principal;
import java.util.Map;

@Slf4j
@Configuration
//注解开启STOMP协议来传输基于代理的消息，此时控制器支持使用@MessageMapping
@EnableWebSocketMessageBroker
public class WebSocketConfig //extends AbstractWebSocketMessageBrokerConfigurer {
        implements WebSocketMessageBrokerConfigurer {
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        // withSockJS 声明启用支持 sockJS
        registry.addEndpoint("/webServer").withSockJS();//.setAllowedOrigins("*")
        registry.addEndpoint("/queueServer").addInterceptors(new SessionAuthHandshakeInterceptor()).
                setHandshakeHandler(new DefaultHandshakeHandler(){
            @Override
            protected Principal determineUser(ServerHttpRequest request, WebSocketHandler wsHandler, Map<String, Object> attributes){
                //JSONObject user = (JSONObject)attributes.get("user");
                //log.info("{}",user);
                //JSONObject  user = BeanUtil.toBean(SecurityUtil.currentUserObj(), JSONObject.class);
                log.info("{}",attributes.get("user"));
                return new MyPrincipal(attributes.get("user").toString());//user.getStr("username")
            }
        }).withSockJS();//注册两个STOMP的endpoint，分别用于广播和点对点
    }
    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        //topic用来广播，user用来实现p2p
        config.enableSimpleBroker("/topic", "/user");
    }
}
class MyPrincipal implements Principal{
    String name="";
    public MyPrincipal(String name){
        this.name=name;
    }

    @Override
    public String getName() {
        return this.name;
    }
}